const express = require('express');
const path = require('path'); // 引入 path 模块
const app = express();
const morgan = require('morgan');
const helmet = require('helmet');
const cors = require('cors');
const routes = require('./routes');
const config = require('./config');
const jwt = require('jsonwebtoken');
const errorHandler = require('./middlewares/errorHandler');

app.use(helmet()); // 安全中间件
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'", "'unsafe-eval'", "cdnjs.cloudflare.com", "cdn.jsdelivr.net", "unpkg.com"], // 允许内联脚本
      styleSrc: ["'self'", "'unsafe-inline'", "cdnjs.cloudflare.com"], // 允许内联样式
      imgSrc: ["'self'", "data:", "https://randomuser.me"], // 添加随机用户图片源
      fontSrc: ["'self'", "cdnjs.cloudflare.com"],
      connectSrc: ["'self'"]
    }
  })
);

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use(morgan('dev')); // 日志

// 设置静态文件目录
app.use(express.static(path.join(__dirname, '../frontend'), {
  setHeaders: (res, path) => {
    if (path.endsWith('.css')) {
      res.setHeader('Content-Type', 'text/css');
    }
  }
}));

// 静态资源路由
app.use('/img', express.static(path.join(__dirname, '../frontend/img')));
app.use('/css', express.static(path.join(__dirname, '../frontend/css')));
app.use('/js', express.static(path.join(__dirname, '../frontend/js')));
app.use('/webfonts', express.static(path.join(__dirname, '../frontend/css/webfonts')));


// 注册路由
app.use('/api', routes);

// 错误处理中间件
app.use(errorHandler);

// 调整认证中间件 - 只保护需要登录的路由
app.use((req, res, next) => {
  // 定义不需要认证的路径
  const publicPaths = [
    '/',
    '/login.html',
    '/api/login',
    '/img/',
    '/css/',
    '/js/',
    '/webfonts/',
    '/font-awesome/',
    '/api/tourist/*'
  ];

  // 检查当前路径是否在公开路径中
  const isPublic = publicPaths.some(path => {
    if (path.endsWith('*')) {
      return req.path.startsWith(path.slice(0, -1));
    }
    return req.path === path;
  });

  if (isPublic) return next();

  // 需要认证的路由处理
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: '未提供认证令牌' });

  try {
    const decoded = jwt.verify(token, config.jwtSecret);
    req.user = decoded;

    // 检查角色权限
    const path = req.path;
    if (path.startsWith('/api/student') && decoded.role !== 'student') {
      return res.status(403).json({ error: '无学生权限' });
    }
  } catch (err) {
    return res.status(401).json({ error: '无效的认证令牌' });
  }
});


// 根路径重定向到 index.html
app.get('/', (req, res) => { // 新增
  res.sendFile(path.join(__dirname, '../frontend/index.html'));
});

// 404处理
app.use((req, res, next) => {
  res.status(404).json({
    status: 'error',
    message: 'Not found'
  });
});

// 错误处理
app.use((err, req, res, next) => {
  console.error(err.stack);

  // JWT验证错误
  if (err.name === 'UnauthorizedError') {
    return res.status(401).json({
      status: 'error',
      message: '认证失败'
    });
  }

  // 验证错误
  if (err.name === 'ValidationError') {
    return res.status(400).json({
      status: 'error',
      message: err.message || '验证错误'
    });
  }

  res.status(500).json({
    status: 'error',
    message: 'Internal server error'
  });
});

// 调试, 在应用启动后打印所有注册的路由：
app.on('listening', () => {
  const routes = [];
  app._router.stack.forEach(middleware => {
    if (middleware.route) {
      routes.push(`${Object.keys(middleware.route.methods).join(', ')} -> ${middleware.route.path}`);
    } else if (middleware.name === 'router') {
      middleware.handle.stack.forEach(handler => {
        const route = handler.route;
        if (route) {
          routes.push(`${Object.keys(route.methods).join(', ')} -> ${route.path}`);
        }
      });
    }
  });
  console.log('注册的路由:\n', routes.join('\n'));
});

module.exports = app;